<template>
  <el-dialog :title="'选择位置：' + unitTypeName" :visible.sync="showDialog" :close-on-click-modal="false" width="1000px" top="50px" append-to-body @closed="reset">
    <!-- <el-form size="small" inline label-width="80px">
      <el-form-item label="选择">
        <el-select v-model="unitType" placeholder="请选择验收对象" @change="changeUnitType">
          <el-option v-for="item in unitTypeEnum" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form> -->

    <el-empty description="加载中..." v-if="buildingLoading" />
    <el-empty v-else-if="!buildings.length" />
    <el-empty description="暂不支持该验收对象" v-else-if="!unitTypeCpn" />
    <el-container v-else class="content">
      <el-main style="padding: 0">
        <component :is="unitTypeCpn" :buildings="buildings" :is-firezone="isFirezone" :curr-area="currArea" :step.sync="step" @cancel="onCancelPosition" @ok="onSelectPosition" />
      </el-main>
      <el-aside class="rectify-list" width="230px">
        <TaskRectifyList :list="taskRectifyList" @ok="onTaskRectify" />
      </el-aside>
    </el-container>

    <div slot="footer">
      <el-button type="primary" :disabled="buildingLoading || !buildings.length || !unitTypeCpn" @click="btnSubmit">确 定</el-button>
      <el-button v-if="step" @click="step = 0">上一步</el-button>
      <el-button @click="showDialog = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 过程检查-选择区域
import { debounce } from '@/utils'
import { cqRandomAreaType } from '@/utils/baseData'
import { generateTaskRectifyTmpId } from '@/utils/cq'
import { getEnum } from '@/api/common'
import { getCqBuildingList, getTaskRectifyList } from '@/api/projectInspection/courseCheck'
import Buildings from './Buildings'
import Floors from './Floors'
import Rooms from './Rooms'
import Piles from './Piles'
import PublicArea from './PublicArea'
import Direction from './Direction'
import TaskRectifyList from './TaskRectifyList'
// 7-批次 暂时不用
const cpnMap = { 1: 'Floors', 2: 'Rooms', 3: 'Buildings', 4: 'Piles', 5: 'PublicArea', 6: 'Direction', 8: 'PublicArea' }
const areaType2unitType = cqRandomAreaType.reduce((o, i) => !void (o[i.value] = i.unitType) && o, {})
export default {
  name: 'SelectArea',
  components: { Buildings, Floors, Rooms, Piles, Direction, PublicArea, TaskRectifyList },
  data() {
    return {
      showDialog: false,
      rdcScore: { projectId: '', randomId: '', processType: '' },
      rdcAreas: [], // 抽查区域
      currArea: { fileId: '' },
      scoreType: '',
      unitType: 0,
      isFirezone: false,
      unitTypeEnum: [], // 验收对象
      buildingLoading: false,
      buildings: [],
      taskRectifyHistory: {},
      position: {},
      step: 0
    }
  },
  computed: {
    unitType2Label() {
      return this.unitTypeEnum.reduce((o, i) => !void (o[i.value] = i.label) && o, {})
    },
    unitTypeName() {
      return this.isFirezone ? '防火分区' : this.unitType2Label[this.unitType] || ''
    },
    unitTypeCpn() {
      return cpnMap[this.unitType] || ''
    },
    taskRectifyList() {
      const { projectId } = this.rdcScore
      const { unitType } = this
      if (!projectId || !unitType) return []
      const list = this.taskRectifyHistory[projectId] || []
      // 进行 unitType 过滤
      return list.filter(i => i.tmpId.startsWith(`${unitType}_`))
    }
  },
  created() {
    this.btnSubmit = debounce(this.onSubmit, 1e3, true)

    getEnum('unitType').then(res => {
      const data = res.data.unitType || []
      // 过滤掉"批次"
      this.unitTypeEnum = data.filter(i => i.value !== 7)
    })
  },
  methods: {
    reset() {
      this.buildingLoading = false
      this.buildings = []
      this.position = {}
      this.step = 0
    },
    open(data = {}) {
      const { rdcScore, rdcAreas, currArea, scoreType, unitType, isFirezone } = data
      if (!rdcScore?.projectId || !rdcScore.randomId || !rdcScore.processType || !currArea?.fileId || !scoreType || !unitType) return this.$message.error('数据错误，缺少参数')

      this.rdcScore = rdcScore
      this.rdcAreas = rdcAreas || []
      this.currArea = currArea
      this.scoreType = scoreType
      this.unitType = unitType
      this.isFirezone = !!isFirezone || unitType === 8
      this.getBuildings()
      this.getTaskRectifyList()
      this.showDialog = true
    },
    async getBuildings() {
      const { projectId, randomId } = this.rdcScore
      const { unitType } = this
      this.buildingLoading = true
      const res = await getCqBuildingList({ projectId, randomId }).catch(() => false)
      this.buildingLoading = false
      if (res === false) return (this.buildings = [])

      let data = res.data || []
      data.sort((a, b) => a.fnumber.localeCompare(b.fnumber))
      // 3-楼栋，过滤其他非楼栋数据
      if (unitType === 3) data = data.filter(i => !i.publicareatype)

      this.buildings = data
    },
    async getTaskRectifyList() {
      // 获取历史数据，合并到当前缓存
      const { projectId, randomId } = this.rdcScore
      const { rdcAreas, scoreType, unitType } = this
      const list = this.taskRectifyHistory[projectId] || []
      const tmpIds = list.map(i => i.tmpId)

      // 将抽查区域加入历史列表
      rdcAreas.map(i => {
        if (i.isDel) return
        const unitType = areaType2unitType[i.randomType]
        if (!unitType) return
        const tmpId = generateTaskRectifyTmpId(unitType, i)
        if (!tmpId || tmpIds.includes(tmpId)) return
        tmpIds.push(tmpId)
        list.push({ ...i, tmpId, shortName: i.areaName })
      })

      const res = await getTaskRectifyList({ taskId: randomId, unitType }).catch(() => false)
      if (res === false) return

      const data = res.data || []
      data.map(i => {
        const tmpId = generateTaskRectifyTmpId(unitType, i)
        if (!tmpId) return

        if (tmpIds.includes(tmpId)) {
          // 位置相同时，保留与 scoreType 相同的项
          if (i.standardType === scoreType) {
            // 移除
            const index = list.findIndex(r => r.tmpId === tmpId)
            list.splice(index, 1)

            i.tmpId = tmpId
            list.push(i)
            return
          }
          return
        }

        i.tmpId = tmpId
        tmpIds.push(tmpId)
        list.push(i)
      })
      this.$set(this.taskRectifyHistory, projectId, list)
    },
    addToHistory(position) {
      const { projectId } = this.rdcScore
      const { unitType } = this
      const list = this.taskRectifyHistory[projectId] || []

      const tmpId = generateTaskRectifyTmpId(unitType, position)
      if (!tmpId) return

      // 已存在先移除
      const index = list.findIndex(i => i.tmpId === tmpId)
      if (index > -1) list.splice(index, 1)

      position.tmpId = tmpId
      list.unshift(position)
      this.$set(this.taskRectifyHistory, projectId, list)
    },
    changeUnitType() {
      this.step = 0
    },
    onCancelPosition() {
      this.position = {}
    },
    onSelectPosition(data) {
      this.position = data.position
      if (data.submitNow) this.onSubmit()
    },
    onTaskRectify(data) {
      this.position = data.position
    },
    async onSubmit() {
      const { unitType, position, unitTypeName } = this
      const showMsg = msg => this.$message.info(`请选择${msg || unitTypeName}`)

      // 1 2 3 6 指楼栋ID；4-桩基，5-公区，8-防火分区 指自己
      if (!position.buildingId) return showMsg([1, 2, 3, 6].includes(unitType) ? '楼栋' : '')
      if (unitType === 1) {
        if (!position.floor) return showMsg()
      } else if (unitType === 2) {
        if (!position.roomId) return showMsg()
      } else if (unitType === 6) {
        if (!position.direction) return showMsg()
      }

      this.$emit('ok', { position })
      this.addToHistory(position)
      this.showDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  height: calc(100vh - 350px);
  overflow: auto;
}
.rectify-list {
  padding: 0px;
  margin: 0 0 0 10px;
  background: none;
}
</style>
